package com.ljx.itbbs.server.mall.service.strategy;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ljx.itbbs.common.utils.AssertUtil;
import com.ljx.itbbs.server.mall.dao.OrderDao;
import com.ljx.itbbs.server.mall.domain.entity.OrderEntity;
import com.ljx.itbbs.server.mall.domain.enums.OrderTypeEnum;
import com.ljx.itbbs.server.mall.domain.vo.req.OrderSaveReq;
import com.ljx.itbbs.server.mall.service.adapter.OrderAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.lang.reflect.ParameterizedType;
import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description: 订单处理抽象类
 * @Date: 2024-03-29  17:20
 */
public abstract class AbstractOrderHandler<Req> {

    @Autowired
    private OrderDao orderDao;

    private Class<Req> bodyClass;

    @PostConstruct
    private void init() {
        ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
        this.bodyClass = (Class<Req>) genericSuperclass.getActualTypeArguments()[0];
        OrderHandlerFactory.register(getOrderTypeEnum().getType(), this);
    }

    abstract OrderTypeEnum getOrderTypeEnum();

    abstract String getOrderObjId(Long objId);

    abstract String getOrderDesc(Long objId);


    @Transactional
    public Long saveOrder(OrderSaveReq req, Long userId){
        // 获取描述
        String desc = getOrderDesc(req.getObjId());
        String objId = getOrderObjId(req.getObjId());
        // 检查是否已经保存
        AssertUtil.isFalse(check(objId), "订单已存在，请前往个人中心支付");
        // 保存订单
        OrderEntity order = OrderAdapter.buildOrderSave(req, userId, objId, desc);
        orderDao.save(order);

        return order.getId();
    }

    private Boolean check(String finalObjId){
        OrderEntity orderEntity = orderDao.getByObjId(finalObjId);
        return Objects.nonNull(orderEntity);
    }

}
